<?php
namespace app\mp\admin;
use app\common\service\Order as OrderService;
use app\common\service\SkuTailBill;
use app\common\service\Sku as SkuService;
use app\system\admin\Admin;
use think\Db;

class TailManage extends Admin
{
    /**
     * 尾货管理
     *
     * @author hhx
     * @date 2022年8月3日
     */
    public function index()
    {
        $action = $this->request->param('action/s', '');
        $status       = $this->request->param('status/s', 0);

        $getClientOrdernum= $this->request->param('client_ordernum/s', '');
        $factoryKV = getFactoryKV(false);
        $sizeList = getSizeKV(false);
        $stallsKV= getStallsKV();
        $data = [];
        //尾货待处理-修改尾货差异
        if($action=='changeSkuDiff'){
            return $this->_changeSkuDiff();
        }

        //详细
        if($action=="detailList"){
            return $this->_detailList();
        }

        if ($this->request->isAjax() || $this->request->param('export')) {
           // 获取分页参数
           $page       = $this->request->param('page/d', 1);
           $limit      = $this->request->param('limit/d', 20);
           $export     = $this->request->param('export/d', 0);
           $sku = $this->request->param('sku', '');
           $where=[];
           $orderData=[];

           if ($export) {
               set_time_limit(0);
               $page = 1;$limit = 99999;
           }

           //status:  0入库待处理，1出库待处理, 2MSN库存差异、3已完成
           switch ($status){
               case 0:
                   if($getClientOrdernum !=''){
                       if($sku) $where[] = ['o.sku', '=', $sku];
                       $orderData= $this->_PendingTailAction($where,$page,$limit,-1);
                   }
                   break;
               case 1:

                   if($getClientOrdernum !='') {
                       if ($sku) $where[] = ['o.sku', '=', $sku];
                       $orderData = $this->_PendingTailAction($where, $page, $limit, -2);
                   }
                   break;
               case 2:
                   $orderData= $this->_mesStockDiff($where,$page,$limit);
                   break;
               case 3:
                   $orderData= $this->_doneTail($where,$page,$limit);
                   break;
           }
            $total=isset($orderData['total'])?$orderData['total']:0;

            //扫码出、入库时，判断当前搜索提交过来的订单是出库还是入库，并修改对应 status值
            if(isset($orderData['stock_outtype'])){
                $data['status'] = $status;
                //数据不能为空
                if($total>0){
                    //如果是出库 赋值为1
                    if($orderData['stock_outtype']==-2) {
                        $status=1; $data['status'] = 1;
                    };
                }
            }else{
                $data['status'] = $status;
            }

           //统计-tab中订单条数
           $data['statData']= $this->StatisTabNum($data['status'],$total);
           $data['totaldata']=$total;
           $data['data'] = isset($orderData['list'])?$orderData['list']:[];

           //导出
           if ($export) {
               $this->DataExpXls('尾货管理列表-' .date('YmdHis'), $data['data'],$data['status']);
               exit;
           }
           $data['count'] = $total;
           $data['code'] = 0;
           $data['client_ordernum'] =$getClientOrdernum;
           $data['msg'] = '';

           return json($data);
        }
        $statData=[0,0,0,0,0];
        $assign = [
            'status' => $status,
            'sizeList' => [0 => '请选择'] + $sizeList,
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'statData'=>$statData,
            'stallsKV' => ['' => '请选择'] + $stallsKV,
            'clientStatus' => config('mimo.client_status'),
        ];

        return $this->assign($assign)->fetch();
    }

    /**
     * MES库存差异
     * @author: huanghuixiang
     * @date: 2022/9/22 9:27
     */
    public function _mesStockDiff($where,$page,$limit){
        $result=[];
        $where0=[];
        $sku = $this->request->param('sku', '');
        $factory_id = $this->request->param('factory_id', '');

        if(!empty($sku)) $where[]=['t.sku','=',$sku];
        if(!empty($factory_id)) $where0[]=['st.factory_id','=',$factory_id];
        //mes库存差异 只能看到当前用户所属工厂
        if(FACTORY_IDS !='*' && FACTORY_IDS !='' && empty($factory_id) ) {
            $factoryList=explode(',',FACTORY_IDS);
            $where0[] = ['st.factory_id', 'in', $factoryList];
        }

        $where[]=['totalnum','>',0];
        $field='st.sku,st.size_name,sum(available_count) as totalnum,ifnull(stm.mes_count,0) as mes_count,st.factory_id';
        $field .=',sk.ori_pic,f.name as factory_name';
        $field .=',stm.update_time,stm.sync_status';
        $sql=db('sku_stock st')->field($field)
               ->join('sku_stock_mes stm','st.sku=stm.sku and st.size_name=stm.size_name','left')
               ->join('sku sk', 'st.sku = sk.sku','left')
               ->join('factory f', 'st.factory_id = f.id','left')
               ->where($where0)
               ->group('st.sku,st.size_name')
               ->buildSql();
        //统计
        $result['total']=DB::table($sql.' t')->where('t.totalnum <> t.mes_count')->where($where)->count();
        //列表
        $result['list']=DB::table($sql.' t')->field('t.*,(t.mes_count - t.totalnum) as diff_num')->where('t.totalnum <> t.mes_count')->where($where)->orderRaw("diff_num desc")->page($page)->limit($limit)->select();

        foreach ($result['list'] as $key=>$val){
            $diff=$val['mes_count']-$val['totalnum'];
            $result['list'][$key]['mes_tail_dff']=$diff;
            $result['list'][$key]['pack_status_stay']="待修正";

            if($val['sync_status']==1){
                $result['list'][$key]['tip_message']="";
            }else{
                if($diff < 1){
                    $result['list'][$key]['tip_message']="去MES新增加";
                }
                else{
                    $result['list'][$key]['tip_message']="去MES修改";
                }
            }
        }
        return $result;
    }


    /**
     *  统计-tab中订单条数
     * @date 2022/9/3
     * @author huanghuixiang
     * param  status:  0入库待处理，1出库待处理, 2MSN库存差异、3已完成
     */
    public function StatisTabNum($status,$total){

        $sku = $this->request->param('sku', '');
        $client_ordernum = $this->request->param('client_ordernum', '');

        $SkuTailBill=new SkuTailBill();

        //status 0、1, 出库待处理、入库待处理- 总数
        $checkin_num=0;
        $out_num=0;
        if(!empty($client_ordernum)){
            $stock_in_out_num =$SkuTailBill->getOutStackTotalNum($sku,$client_ordernum);
            $checkin_num=$stock_in_out_num[0];
            $out_num=$stock_in_out_num[1];
        }
        //status 2, MES尾货差异-总数
        $mes_num=$SkuTailBill->getMesNum($sku);

        //status 3, 已完成-总数
        $done_num =$SkuTailBill->getTailDoneData($sku,$client_ordernum);
        //拼接
        $data=[$checkin_num,$out_num,$mes_num,$done_num];
        foreach ($data as $key=>$val){
            if($status==$key){
                $data[$key]=$total;
            }
        }

        return $data;
    }

    //更新MES库存表同步状态
    public function applyMesSync(){
        $sku=$this->request->param('sku/s');
        $size_name=$this->request->param('size_name/s');
        if(!empty($size_name) && !empty($sku)){
            db('sku_stock_mes')->where(['sku'=>$sku,'size_name'=>$size_name])->update(['sync_status'=>1]);
        }
        return $this->Json(1,'成功');
    }


    /**
     * 入库操作
     * @author hhx
     * 2022-08-18
     */
    public function stockCheckIn(){

        $orderId = $this->request->param('order_id');
        $sizeName=$this->request->param('size_name');
        $count=$this->request->param('count');
        $dressCode=trim($this->request->param('dress_line_code'),";");
        $stockType=$this->request->param('stocktype');
        $tail_goods_dff=$this->request->param('tail_goods_dff',0);
        $is_tail_manage=$this->request->param('is_tail_manage','');
        $need_put_num=$this->request->param('need_put_num',0);
        $defective_reason=$this->request->param('defective_reason');
        $orderService = new OrderService();
        $SkuTailBill= new SkuTailBill();
        $orderInfo = $orderService->getInfoById($orderId, 'sku,id as order_id,client_ordernum,factory_id');
        $dressCode=$dressCode.";";
        $dressCodeArr=explode(";",$dressCode);
        unset($dressCodeArr[count($dressCodeArr)-1]);
        foreach ($dressCodeArr as $key=>$dressCodeStr){
            $newDressArr[$dressCodeStr]=$key;
        }
        if(empty($orderInfo)){
            return $this->Json(0,'订单号有误,请确认');die;
        }
        if(empty($sizeName)){
            return $this->Json(0,'尺码不能为空');die;
        }

        if(count($newDressArr)>1){
            return $this->Json(0,'存在不同的条码,请确认');die;
        }
        $oldstock=0;

        $oldStockInfo=db('sku_stock')->where(['sku' => $orderInfo['sku'], 'factory_id' => $orderInfo['factory_id'],'size_name'=>$sizeName,'client_ordernum' => $orderInfo['client_ordernum']])->find();

        $has_dress_code=db('sku_stock')->where(['dress_line_code' => $dressCodeArr[0]])->find();

        if($oldStockInfo && $oldStockInfo['dress_line_code']!=$dressCodeArr[0] && !empty($oldStockInfo['dress_line_code'])){
            return $this->Json(0,$sizeName.'已入库，条码为'.$oldStockInfo['dress_line_code'].',请确认当前条码');die;
        }
        if($has_dress_code ){
            if($has_dress_code['size_name']!=$sizeName || $has_dress_code['sku']!=$orderInfo['sku'] || $has_dress_code['client_ordernum']!=$orderInfo['client_ordernum']){
                return $this->Json(0,'条码'.$dressCodeArr[0].'已入库,对应订单号：'.$has_dress_code['client_ordernum'].',尺码：'.$has_dress_code['size_name'].'');die;
            }
        }


        try {
            db()->startTrans();
            $actiontime=time();
            $savedata = ['sku' => $orderInfo['sku'],'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'available_count' =>count($dressCodeArr),'size_name'=>$sizeName, 'dress_line_code'=>$dressCodeArr[0],'factory_id'=>$orderInfo['factory_id'],'update_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($savedata['available_detail']);unset($savedata['available_count']);
                $savedata['defective_count']=count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$savedata['defective_reason']=$defective_reason;
            }
            if(!$oldStockInfo){
                $savedata['create_time']=$actiontime;
                db('sku_stock')->insert($savedata);
            }else{
                $oldstock=$oldStockInfo['available_count'];
                $savedata['dress_line_code']=$dressCodeArr[0];
                $savedata['available_detail']='{"'.$sizeName.'":"'.($oldstock+count($dressCodeArr)).'"}';
                $savedata['available_count']=$oldStockInfo['available_count']+count($dressCodeArr);
                if($stockType=='defective'){
                    unset($savedata['available_detail']);unset($savedata['available_count']);
                    $savedata['defective_count']=$oldStockInfo['defective_count']+count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.($oldStockInfo['defective_count']+count($dressCodeArr)).'"}';
                    $savedata['defective_reason']=$defective_reason;
                }
                db('sku_stock')->where(['id' => $oldStockInfo['id']])->update($savedata);
            }
            $stock_log = ['sku' => $orderInfo['sku'], 'uid' =>ADMIN_ID,'action_type' => 1,'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'factory_id' =>$orderInfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($stock_log['available_detail']);
                $stock_log['defective_count']=count($dressCodeArr);
                $stock_log['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$stock_log['defective_reason']=$defective_reason;$stock_log['remark']=$defective_reason;
            }else{
                $stock_log['available_count']=count($dressCodeArr);
            }
            db('sku_stock_log')->insert($stock_log);

            /**
             * 判断是该订单在尾货表是否存在，不存在新增，否则更新。
             * 操作表 sku_tail_bill
             */
            $where=['client_ordernum' => $orderInfo['client_ordernum'],'size_name'=>$sizeName];

            //产品经理定义的需求： 新增入库单的订单，尾货差异为0的也可以出库，直接 尾货差异数=扫码的数量，让它完成任务
            if($is_tail_manage== -1){
                if($tail_goods_dff<0)  $tail_goods_dff  = abs($tail_goods_dff);
                if($tail_goods_dff==0){
                    $tail_goods_dff=count($dressCodeArr);
                }
            }
            $diffnum=$tail_goods_dff-count($dressCodeArr);

            $bill_info=db('sku_tail_bill')->where($where)->findOrEmpty();

            if(count($bill_info)>=1){
                $orderInfo['tail_goods_dff']= $diffnum<=0 ?0:$diffnum;
                $orderInfo['update_time']=time();
                $orderInfo['admin_id']=ADMIN_ID;
                $SkuTailBill->updateTailBill($where,$orderInfo);
            }else{
                $orderInfo['status']=0;
                $orderInfo['size_name']=$sizeName;
                $orderInfo['tail_goods_dff']=$diffnum<=0 ?0:$diffnum;
                $orderInfo['need_put_num']=$need_put_num;
                $orderInfo['origin_type']=0;
                $orderInfo['is_get_into']=1;
                $orderInfo['admin_id']=ADMIN_ID;
                $orderInfo['update_time']=time();
                $orderInfo['create_time']=time();
                $SkuTailBill->addTailBill($orderInfo);
            }
            //如果入库数量等于尾货差异，直接完成更新-> order_size
            if($diffnum <=0 ){
                $SkuTailBill->updateTailInfo($where);
                //搜索的 订单条数，次处针对尾货完成后，是否要继续下去。diffnum 大于0会继续弹出窗口
                if($count=="undefined") $count=1;
                $diffnum=$count-1;
            }

            $postParm=[];
            $postParm['client_ordernum']=$orderInfo['client_ordernum'];
            $postParm['size_name']=$sizeName;
            $postParm['sku']=$orderInfo['sku'];
            $postParm['addNum']=count($dressCodeArr);
            //新增加库存->将数量推送到mes
            $res= (new SkuService())->skuStockUptoMesV2($postParm);
            $this->addOrderLog($orderId, $orderInfo['client_ordernum'], $res['msg']);

            db()->commit();
            $savedata['checkin_count']=count($dressCodeArr);
            $savedata['size_name']=$sizeName;
            $savedata['tail_goods_dff']=$diffnum;
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 扫码出库操作
     * @author hhx
     */
    public function stockCheckOut(){
        $jump=0;
        $idlist= $this->request->param('order_id');
        $tail_goods_dff=$this->request->param('tail_goods_dff',0);
        $count=$this->request->param('count',0);
        $is_tail_manage=$this->request->param('is_tail_manage',0);
        $client_ordernum=$this->request->param('client_ordernum',0);
        $need_put_num=$this->request->param('need_put_num',0);
        $dressCode=trim($this->request->param('out_dress_line_code'),"\n");
        $orderId_list=array_filter(explode(',',$idlist));
        $orderInfo_list = db('order')->field('sku,client_ordernum,factory_id')->where('id','in',$orderId_list)->select();
        $dressCodeArr=explode("\n",$dressCode);
        $newDressArr=[];



        foreach ($dressCodeArr as $key=>$dressCodeStr){
            if(!isset($newDressArr[$dressCodeStr])){
                $newDressArr[$dressCodeStr]=1;
            }else{
                $newDressArr[$dressCodeStr]++;
            }
        }

        $sku_list=array_column($orderInfo_list,'sku');
        $stockList=db('sku_stock')->where(['sku' => $sku_list,'dress_line_code'=>array_keys($newDressArr)])->select();
        if(count($stockList)<count($newDressArr)){
            return $this->Json(0,'出库条码有误，有不存在的出库条码');die;
        }
        $orders=array_unique($orderId_list);
        if(count($orders)>1){
            return $this->Json(0,'暂时不支持 同时选择多个订单出库！');die;
        }

        $availableCountArr=array_column($stockList,'available_count','dress_line_code');
        foreach ($availableCountArr as $index=>$stockcount){
            if($newDressArr[$index]>$stockcount){
                return  $this->Json(0,$index.'出库数量'.$newDressArr[$index].'件超过总库存'.$stockcount.'件，库存不足,请确认');die;
            }
        }

        try {
            db()->startTrans();

            $actiontime=time();
            $act_ret_str='';
            $SkuTailBill= new SkuTailBill();
            foreach ($stockList as $key=>$stockinfo){
                $now_available_count=$stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']];

                $savedata = ['sku' => $stockinfo['sku'],'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.($stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']]).'"}',
                    'available_count' =>$now_available_count,'update_time' => $actiontime];

                db('sku_stock')->where(['id' => $stockinfo['id']])->update($savedata);
                $stock_log = ['sku' => $stockinfo['sku'], 'uid' =>ADMIN_ID,'available_count'=>$newDressArr[$stockinfo['dress_line_code']],'out_ordernum'=>$client_ordernum,
                    'action_type' => 2,'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.$newDressArr[$stockinfo['dress_line_code']].'"}',
                    'factory_id' =>$stockinfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$stockinfo['client_ordernum'],'remark'=>$client_ordernum."出货调用"];
                db('sku_stock_log')->insert($stock_log);
                $act_ret_str=$act_ret_str.$stockinfo['size_name'].":".$newDressArr[$stockinfo['dress_line_code']]."件，";


                /**
                 * 判断是该订单在尾货表是否存在，不存在新增，否则更新。
                 * 操作表 sku_tail_bill
                 */
                $where=['client_ordernum' => $client_ordernum,'size_name'=>$stockinfo['size_name']];
                $bill_info=db('sku_tail_bill')->where($where)->findOrEmpty();

                //产品经理定义的需求： 新增出库单的订单，尾货差异为0的也可以出库，直接 尾货差异数=扫码的数量，让它完成任务
                if($is_tail_manage== -2){
                    if($tail_goods_dff==0)   $tail_goods_dff=$newDressArr[$stockinfo['dress_line_code']];
                    if($tail_goods_dff>0){
                        $tail_goods_dff *= -1;
                    }
                }

                $diffnum=$tail_goods_dff+$newDressArr[$stockinfo['dress_line_code']];

                if( $tail_goods_dff !=0 && $diffnum>0){
                    return $this->Json(0,'出库数量：'.$newDressArr[$stockinfo['dress_line_code']].' 已超过尾货差异数量：'.$tail_goods_dff.' ,请确认');die;
                }
                if($tail_goods_dff==0){
                    $diffnum =0;
                }

                $orderInfo=[];
                if(empty($bill_info)){
                    $orderInfo['order_id']= $idlist;
                    $orderInfo['sku']= $stockinfo['sku'];
                    $orderInfo['factory_id']= $stockinfo['factory_id'];
                    $orderInfo['client_ordernum']= $client_ordernum;
                    $orderInfo['status']=1;
                    $orderInfo['size_name']=$stockinfo['size_name'];
                    $orderInfo['tail_goods_dff']=$diffnum;
                    $orderInfo['need_put_num']=$need_put_num;
                    $orderInfo['admin_id']=ADMIN_ID;
                    $orderInfo['origin_type']=0;
                    $orderInfo['is_get_into']=1;
                    $orderInfo['update_time']=time();
                    $orderInfo['create_time']=time();
                    $SkuTailBill->addTailBill($orderInfo);
                }else{
                    $orderInfo['tail_goods_dff']=$diffnum;
                    $orderInfo['update_time']=time();
                    $orderInfo['admin_id']=ADMIN_ID;
                    $SkuTailBill->updateTailBill($where,$orderInfo);
                }
                //如果出库数量等于尾货差异，直接完成更新-> order_size
                if($diffnum ==0){
                    $SkuTailBill->updateTailInfo($where);
                    $diffnum =$count-1;

                }
                //当库存为零或 尾货差异为0，跳转到MES修改库存, $jump大于0的时候 代表还需要跳转
                if($diffnum ==0 || $now_available_count==0){
                    $jump=1;
                }
            }

            db()->commit();
            $savedata['act_ret_str']=$act_ret_str;
            $savedata['tail_goods_dff']=abs($diffnum);
            $savedata['jump']=$jump;
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    //详细
    public function _detailList(){

        $val        = $this->request->param('val/d', 0);
        $status        = $this->request->param('status/s', 0);
        $a        = $this->request->param('a/s', '');
        $id_list=$this->request->param('id_list', 0);
        $id_num_list=array_filter(explode(',',$id_list));
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $data['data']=[];

            if($status==2){
                $group_diff='pd.sku';
                $field_diff='sum(tail_goods_dff) as total_num,sku';
                $where[]=['pd.sku','in',$id_num_list];
            }else{
                $where[]=['pd.client_ordernum','in',$id_num_list];
                $group_diff='pd.client_ordernum';
                $field_diff='(sum(need_put_num) -sum(tail_goods_dff)) as total_num,client_ordernum';
            }
            $data['data']= db('sku_tail_bill pd')
                ->join('sku sk ', ' pd.sku=sk.sku','left')
                ->join('factory f', 'pd.factory_id = f.id','left')
                ->field('pd.*,sk.ori_pic,f.name as factory_name,su.nick')
                ->join('system_user su','pd.admin_id= su.id','left')
                ->where($where)
                ->select();
            foreach ($data['data'] as $keyNum=>$valNum){
                //无需处理的
                if($valNum['is_reason']>=1) {
                    $data['data'][$keyNum]['over_status']=2;
                //已经尾货差异为零的，显示已完成
                }if($valNum['tail_goods_dff']==0){
                    $data['data'][$keyNum]['tail_goods_dff']=$valNum['need_put_num'];
                    $data['data'][$keyNum]['over_status']=1;
                }else{
                    $data['data'][$keyNum]['over_status']=0;
                    $data['data'][$keyNum]['tail_goods_dff']=$valNum['need_put_num']-$valNum['tail_goods_dff'];
                    $data['data'][$keyNum]['diffNum']=$valNum['tail_goods_dff'];
                }

            }

            $data['count'] = db('sku_tail_bill pd')->where($where)->count('id');
            $diff_data = db('sku_tail_bill pd')->field($field_diff)->where($where)->group($group_diff)->select();

            $total_count='';
            //前端页面显示总数统计
            foreach ($diff_data as $key=>$value){
                if($status==2){
                    $strnum="sku：".$value['sku'];
                }else{
                    $strnum="订单号：".$value['client_ordernum'];
                }
               $total_count .=$strnum.",&nbsp;&nbsp;总数：".$value['total_num']."；";
            }

            $data['data']= array_values($data['data']);
            $data['total_count'] = $total_count;
            $data['code'] = 0;
            $data['msg'] = '';
            $data['status']=$status;

            return json($data);
        }
        $assign = [
            'val'=>$val,
            'id_list'=>$id_list,
            'status'=>$status,
            'a'=>$a
        ];
        $template = $this->request->param('template', 'detail_list');
        return $this->assign($assign)->fetch($template);
    }


    /**
     * 入库待处理、出库待处理
     * @param $where
     * @param $page
     * @param $limit
     * @param $stock_outtype  -2为出库,-1为出库 ： 这边将 （裁床数-订单数）大于0定义为出库，小于0定义为入库
     * @return array
     * @author: huanghuixiang
     * @date: 2022/9/19 11:25
     */
    public function  _PendingTailAction($where,$page,$limit,$stock_outtype){

        $size_name = $this->request->param('size_name', '');
        $status = $this->request->param('status', 0);
        $client_ordernum   = $this->request->param('client_ordernum', '');
        $factoryId   = $this->request->param('factory_id/d', 0);
        $resault=[];
        $where1=$where2=$where3=[];

        if(!empty($client_ordernum)){
            //默认情况下：传递过来的订单号是要出库还是入库
            if(empty($status)){
                $stock_outtype=$this->judgeOrderType($client_ordernum);
            }else if($status==1){
                $stock_outtype=-2;
            }
            $where[] = ['o.client_ordernum', '=', $client_ordernum];
            $where3=$where;
        }
        if(!empty($factoryId)) $where[] = ['o.factory_id', '=', $factoryId];
        if(!empty($remark)) $where[] = ['t2.size_name', '=', $size_name];
        if(!empty($size_name)) $where[] = ['t2.size_name', '=', $size_name];
        if(!empty($where))$where1=$where;

        $field="o.sku,o.id as order_id,o.remark,o.tail_over_time,t2.is_tail_manage,t2.factory_id,t2.size_name,t2.client_ordernum,t2.order_count,t2.shicai_count,
t2.jiaohuo_count,t2.daohuo_count,t2.jiaohuo_tail_count,(cast(t2.shicai_count as signed) - cast(t2.order_count as signed)) as order_goods_dff,
t2.tail_stock_in_out,sk.stock_finished,sk.ori_pic,f.name as factory_name";

        $where1[] = ['t2.is_tail_manage','=',0];
        $where2[]= ['t6.shicai_count','>',0];//实裁数大于0

        //出库: stock_outtype =-2, is_tail_manage=-2、
        //入库: stock_outtype=-1,  is_tail_manage=-1
        if($stock_outtype==-2){
            $where2[]= ['t6.order_goods_dff','<=',0];//尾货差异小于0
            $where3[]= ['t2.is_tail_manage','=',-2];//新增出库单
            $field .=",(cast(t2.order_count*1.3 as signed)- cast(t2.shicai_count as signed)) as tail_goods_dff"; //计算可处理数
            $field2=$field.',@stock_count:=0 AS stock_count ';
        }
        else{
            $field .=",( cast(t2.shicai_count as signed)-cast(t2.order_count*1.3 as signed)) as tail_goods_dff";//计算可处理数
            $field2=$field.'';
            $where2[]= ['t6.order_goods_dff','>',0];//裁床数-订单数大于0
            $where2[]= ['t6.tail_goods_dff','>',0];//尾货差异大于0
            $where3[]= ['t2.is_tail_manage','=',-1];//新增入库单
        }

        $totalsqlson = db('order o')
            ->join('order_size t2', 'o.id = t2.order_id','left')
            ->join('sku sk', 'o.sku = sk.sku','left')
            ->join('factory f', 'o.factory_id = f.id','left')
            ->where($where1)
            ->field($field)
            ->buildSql();
        $orderDataModel=Db::table($totalsqlson.' t6')->where($where2);
        $sql1=$orderDataModel->buildSql();
        $sql2 = db('order o')
            ->join('order_size t2', ' o.id=t2.order_id','left')
            ->join('sku sk', 'o.sku = sk.sku','left')
            ->join('factory f', 'o.factory_id = f.id','left')
            ->where($where3)
            ->field($field2)
            ->buildSql();

        //出库: stock_outtype == -2 ，   $sql1+$totalStockSql计算前面的符合出出库的数据（重点：其中的一条件库存不能为0） 、  $sql2计算（新增出库单的数据）
        //入库: stock_outtype=-1 ，     $sql1 计算前面的符合出入库的数据， $sql2计算（新增入库单的数据）
        if($stock_outtype== -2){
            //库存计算，在$totalStockSql里面了。
            $totalStockSql='SELECT t13.* from (SELECT t12.*,(select sum(st.available_count)  from wx_sku_stock st 
             where t12.sku=st.sku  and  t12.size_name =st.size_name GROUP BY st.size_name limit 1) as stock_count from ('.$sql1.')  t12 ) t13  where t13.stock_count >0  ';
            //联合查询 出库sql
            $allSql= '('.$totalStockSql.' union all '.$sql2 .')';
        }else{
            //联合查询 入库sql
            $allSql= '('.$sql1.' union all '.$sql2 .')';
        }
        //统计
        $resault['total']=DB::table($allSql.' t16 ')->count();

        //列表数据
        $list= DB::table($allSql.' t16')->orderRaw("is_tail_manage asc,tail_over_time desc")->page($page)->limit($limit)->select();

        if($resault['total']>0){
            foreach($list as $key=>$val){
                $list[$key]['pack_status_stay']= "待打包";
                if(!empty($val['tail_over_time'])){
                    $list[$key]['tail_over_time']= date("Y-m-d H:i:s",$val['tail_over_time']);
                }
                else  $list[$key]['tail_over_time']='';
                $list[$key]['status']=$status;
                //出入库文字显示
                $stock_type=$val['order_goods_dff'] >0 ? "入库":'出库';
                if($val['is_tail_manage']==-1){
                    $stock_type="入库";
                    $stock_outtype =-1;
                }else if($val['is_tail_manage']==-2){
                    $stock_type="出库";
                    $stock_outtype =-2;
                }
                $list[$key]['pack_status_stay']=$stock_type;

                //获取服装码
                $otherStockList=db('sku_stock')->where(['sku'=>$val['sku'],'size_name'=>$val['size_name']])
                    ->field('dress_line_code')->select();
                $str='';
                foreach ($otherStockList as $value){
                    $str .=$value['dress_line_code'].',';
                }
                $list[$key]['otherStockList_json']=$str;
                //尾货表
                $bill_info= db('sku_tail_bill')->where(['client_ordernum'=>$val['client_ordernum'],'size_name'=>$val['size_name']])->findOrEmpty();

                if($stock_outtype ==-2){
                    $reality_num=$val['tail_goods_dff'];
                    if(abs($val['tail_goods_dff']) >= $val['stock_count'])   $reality_num=$val['stock_count'];;
                    $reality_num *= -1;//换回负数
                    $list[$key]['tail_goods_dff']=$reality_num; //如果是出库，1、尾货差异显示库存数, 2、如果尾货数大于库存数 则显示库存数
                    $list[$key]['status']=1;
                }else{
                    $list[$key]['tail_goods_dff']=$val['tail_goods_dff']; //如果是入库，显示可处理数
                    $list[$key]['status']=0;
                }

                //如果该订单、尺码在尾货单表存在了，代表已做记录，要取表里tail_goods_dff 最新的数据
                if(isset($bill_info['tail_goods_dff'])){
                    $list[$key]['tail_goods_dff']=$bill_info['tail_goods_dff'];
                }
                $list[$key]['handle_num']=$val['tail_goods_dff'];   //可处理数
            }
        }

        $resault['stock_outtype']=$stock_outtype;
        $resault['list']=$list;
        return $resault;
    }

    /**
     * 根据订单号 读取一条数据，判断是出库、还是入库
     * order_goods_dff 为负数的时候是出库，正数为入库
     * @author: huanghuixiang
     * @return int
     * @date: 2022/9/29 13:22
     */
    public function judgeOrderType($client_ordernum)
    {
        $SkuTailBill=new SkuTailBill();
        $where[] = ['t2.client_ordernum','=',$client_ordernum];
        $where[] = ['t2.shicai_count','>',0];
        $where[] = ['t2.is_tail_manage','<=',0];
        $list=db('order o')->field('(cast(t2.shicai_count as signed) - cast(t2.order_count as signed)) as order_goods_dff,t2.size_name,t2.is_tail_manage,o.sku')
            ->join('order_size t2', ' o.id=t2.order_id','left')
            ->where($where)
            ->order('order_goods_dff desc')
            ->select();

        $num=0;
        if(!empty($list)){
            foreach ($list as $key=>$value){
                //当尾货差异为0时候，如有库存 则判断为出库
                if($value['order_goods_dff'] ==0 ){
                    $stock_num=$SkuTailBill->getSkuStockTotal($value['sku'],$value['size_name']);
                    if($stock_num>0){
                        $num =-2;
                    }else{
                        $num =1;
                    }
                }
                if($value['is_tail_manage']== -2 || $value['order_goods_dff'] <0){
                    $num =-2;
                }else if($value['is_tail_manage']== -1 || $value['order_goods_dff'] >0){
                    $num =1;
                }
                break;
            }
        }

        //$num 如为负的是出库，正数为入库
        if($num<0){
            return -2;
        }else{
            return -1;
        }
    }
    //状态
    public function  getTailStatus($status=0,$is_get_into=0){
        $str='';
        if($is_get_into==1)$status=3;
        switch ($status) {
            case 1:
                $str = "待出库";
                break;
            case 2:
                $str = "待修正";
            case 3:
                $str = "已完成";
                break;
            case -1:
                $str = "<font color='#cd5c5c'>已退货</font>";
                break;
            default:
                $str = "待入库";
        }
        return $str;
    }
    //处理原因
    public function  get_reason_content($is_reason,$reason_content){

        switch ($is_reason) {
            case 1:
                $str = "车间补片";
                break;
            case 2:
                $str = "有报废品";
                break;
            case 3:
                $str = $reason_content;
                break;
            default:
                $str = "";
        }
        return $str;
    }

    //已完成
    public function _doneTail($where,$page,$limit){
        $factoryId = $this->request->param('factory_id', '');
        $status = $this->request->param('status', 0);
        $create_time = $this->request->param('create_date_range', '');
        $client_ordernum   = $this->request->param('client_ordernum', '');
        $sku   = $this->request->param('sku', '');

        if(!empty($sku)) $where[] = ['spd.sku', '=', $sku];

        if(!empty($factoryId)) $where[]=['spd.factory_id','=',$factoryId];
        if(!empty($client_ordernum)) $where[] = ['spd.client_ordernum', '=', $client_ordernum];
        if(!empty($create_time)){
            list($startTime, $endTime) = $create_time != '' ? array_map('strtotime', explode('~', $create_time)): '';
           $where[] =  ['spd.create_time', 'between', [$startTime,$endTime]];
        }
        $resault=[];

        //已完成
        if ($status==3){
            if(!empty($status))
                $where[] = ['spd.is_get_into', '=', 1];
            $where1=$where2=$where;
            $where1[]=['spd.status','<',2];
            $where2[]=['spd.status','=',2];
            $group1='spd.client_ordernum';
            $group2='spd.sku';
            $orderby='spd.update_time';
            $field='spd.id,spd.is_reason,spd.status,spd.is_get_into,spd.reason_content,spd.update_time,spd.client_ordernum,spd.create_time,f.name as factory_name_two,su.nick,sum(spd.tail_goods_dff) as total_num,sum(spd.need_put_num) as total_need_num,count(DISTINCT(spd.client_ordernum)) as  total_ordernum';
            //联合查询- 分别group by 订单号和包号，然后将数据集合一起
            $ordersql1= db('sku_tail_bill spd')
                ->join('factory f', 'spd.factory_id = f.id','left')
                ->join('system_user su','spd.admin_id= su.id','left')
                ->where($where1)->group($group1)->field($field)->order($orderby)->buildSql();

            $ordersql2 =db('sku_tail_bill spd')
                ->join('factory f', 'spd.factory_id = f.id','left')
                ->join('system_user su','spd.admin_id= su.id','left')
                ->where($where2)->group($group2)->field($field)->order($orderby)->buildSql();
            $ModelOrder= Db::table($ordersql1.' aa')->union($ordersql2,true);
            $resault['total']=count($ModelOrder->select());
            $list=$ModelOrder->page($page)->order('update_time desc ')->limit($limit)->select();
        //如果是-打包待发货或出库明细
        }
        if($resault['total']>0){
            foreach($list as $key=>$val){
                 //如果是已完成
                if($status==3) {
                    $list[$key]['reason_content']= isset($val['is_reason'])?$this->get_reason_content($val['is_reason'],$val['reason_content']):"";
                    $list[$key]['d_status']= $this->getTailStatus($val['status'],$val['is_get_into']);
                    $list[$key]['tail_goods_dff_end']= $val['total_need_num'];
                    //如为零，直接显示完成的件数
                    if($val['total_num']==0){
                        $list[$key]['total_num'] = $val['total_need_num'];//总单数
                    }else{
                        $list[$key]['total_num'] = $val['total_need_num']-$val['total_num'];//总单数
                    }

                    $list[$key]['total_need_out_num'] = $val['total_need_num'];
                    //如果是MES库存差异，则显示sku
                    if($val['status']==2){
                        $list[$key]['packageOrder_num']= $val['sku'];
                    }else{
                        $list[$key]['packageOrder_num']= $val['client_ordernum'];
                    }
                    if($val['is_reason']>0) $type="无需处理";
                    else if($val['status']==0) $type="入库";
                    else if($val['status']==1) $type="出库";
                    else if($val['status']==2) $type="MES库存差异";
                    else $type="";
                    $list[$key]['type']= $type;
                }
            }
        }
        $resault['list']=array_values($list);
        return $resault;
    }


    //无需处理
    public function  notNeedHandle()
    {
        $param=$this->request->param();

        //ajax提交
        if($this->request->isAjax()){
            $SkuTailBill=new SkuTailBill();
            $data=$param['data'];
            //整理数据
            $info=db('order')->field('sku,factory_id,client_ordernum')->where(['id'=>$data['order_id']])->find();

            $where=['client_ordernum' => $info['client_ordernum'],'size_name'=>$data['size_name']];
            $bill_info=db('sku_tail_bill')->where($where)->findOrEmpty();

            $orderInfo=[];
            if(empty($bill_info)){
                $orderInfo['order_id']= $data['order_id'];
                $orderInfo['size_name']=$data['size_name'];
                $orderInfo['tail_goods_dff']=$data['tail_goods_dff'];
                $orderInfo['need_put_num']=0;
                $orderInfo['status']=$data['status'];
                $orderInfo['is_reason']=$data['reason'];
                $orderInfo['reason_content']=$data['reason_content'];
                $orderInfo['sku']=$info['sku'];
                $orderInfo['factory_id']= $info['factory_id'];
                $orderInfo['client_ordernum']=$info['client_ordernum'];  ;
                $orderInfo['origin_type']=0;
                $orderInfo['is_get_into']=1;
                $orderInfo['update_time']=time();
                $orderInfo['create_time']=time();
                //插入表 order_sku_taill_bill
                $SkuTailBill->addTailBill($orderInfo);
                //完成后 更新表-> order_size
                $SkuTailBill->updateTailInfo($where);
            }
            return $this->success('操作成功', '');
        }

        $assign = [
            'action'=>'',
            'status'=>$param['status'],
            'order_id'=>$param['order_id'],
            'need_put_num'=>$param['need_put_num'],
            'size_name'=>$param['size_name'],
            'tail_goods_dff'=>$param['tail_goods_dff'],
            'isButton' =>1
        ];

        $template = $this->request->param('template', 'not_need_handle');
        return $this->assign($assign)->fetch($template);
    }

    //新增入库单
    public function  addInvoice(){
        $action        = $this->request->param('action/s', '');
        $type        = $this->request->param('type/s');
        $client_ordernum_show        = $this->request->param('client_ordernum/s');
        //ajax提交
        if($action == "addInvoice"){
            $client_ordernum= $this->request->param('client_ordernum/s', '');
            $size_name= $this->request->param('size_name/s', '');
            $size_name=strtoupper($size_name);
            $orderInfo= db('order_size')->where(["client_ordernum"=>$client_ordernum,"size_name"=>$size_name])->find();
            if(!$orderInfo){
                return $this->error('订单号或尺码有误，找不到该信息!');
            }
            //是否在-尾货待处理中
           // $isCountNum= (new SkuTailBill())->doesItExitDeliveryOrder($client_ordernum,$size_name,$type);
          /*  if($orderInfo['is_tail_manage']==1){
                return $this->error('该订单已在入库单中! 或已处理！');
            }*/
            $resault= db('order_size')->where(["client_ordernum"=>$client_ordernum,"size_name"=>$size_name])->update(['is_tail_manage'=>$type]);
            if($resault){
                return $this->success('操作成功', '');
            }else{
                return $this->error('数据异常' );
            }
        }
         $size_list=db('order_size')->field('size_name')->where(["client_ordernum"=>$client_ordernum_show])->select();

        $assign = [
            'client_ordernum_show'=>$client_ordernum_show,
            'size_list'=>$size_list,
            'action'=>'',
            'data'=>'',
            'ids_str'=>'',
            'type'=>$type,
            'stock_m_type'=>'',
            'storehouseKV'=>'',
            'storeshelfKV'=>'',
            'factoryKV' => '',
            'isButton' =>1
        ];
        $template = $this->request->param('template', 'add_invoice');
        return $this->assign($assign)->fetch($template);
    }

    //修改尾货差异
    private function _changeSkuDiff(){
        return $this->success('保存成功', '');
    }



    /**
     * 导出
     *
     */
    public function DataExpXls($fileName, &$data,$status) {
        if($status==0){
            $head = ['订单号','SKU','尺码','工厂','下单数','裁床数','车间数','出货数','尾货差异','状态','出入库方式','尾部完成时间'];
        }else{
            $head = ['大包编号','总件数','总单数','工厂','日期','状态'];
        }
        $params = [];
        $exportdata = [];

        foreach ($data as $k => $v) {
            switch ($status){
                case 0:
                    $exportdata[] = [
                        $v['client_ordernum'],
                        $v['sku'],
                        $v['size_name'],
                        isset($v['factory_name'])?$v['factory_name']:$v['factory_name_two'],
                        $v['order_count'],
                        $v['shicai_count'],
                        $v['jiaohuo_count'],
                        $v['daohuo_count'],
                        $v['tail_goods_dff'],
                        $v['pack_status_stay'],
                        $v['stock_outtype'],
                        $v['tail_over_time']==0 ? '':date('Y-m-d H:i:s', $v['tail_over_time'])
                    ];
                    break;
                default:
                    $exportdata[] = [
                        isset($v['package_num'])?$v['package_num']:$v['client_ordernum'],
                        $v['total_num'],
                        $v['total_ordernum'],
                        isset($v['factory_name'])?$v['factory_name']:$v['factory_name_two'],
                        $v['create_time']==0 ? '':date('Y-m-d H:i:S', $v['create_time']),
                        $v['d_status']

                    ];
            }

        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }
}

